package com.hm.hall.commons.util;

import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author wei
 */
public class Md5Salt {
    // sign salt
    public static final String signSalt = "110";

    // boss系统 SignSalt
    public static final String BOOS_SIGN_SALT = "798792e38e0f49651afe0f49";


    /**
     * sign计算
     * 110minStartPersonNumber3number20roomTitle冷漫HM1的房间sessionTokenc9651af6c477798792e38e0f49f2cfe6userId2000002110
     *
     * @param parameterMap 请求
     * @throws UnsupportedEncodingException
     */
    private static String makeSign(String signSalt, Map<String, Object> parameterMap) throws UnsupportedEncodingException {
        TreeMap<String, Object> sorted = new TreeMap<String, Object>(parameterMap);
        StringBuilder sb = new StringBuilder(signSalt);
        for (String key : sorted.keySet()) {
            if (!"sign".equals(key) && !key.startsWith("file_")) {
                String[] obj = (String[]) sorted.get(key);
                sb.append(key).append(obj[0]);
            }
        }
        sb.append(signSalt);
        return DigestUtils.md5DigestAsHex(sb.toString().replaceAll("[^\\w]", "").getBytes("utf-8")).toUpperCase();
    }


    /**
     * sign计算
     *
     * @param parameterMap
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String makeSign(Map<String, Object> parameterMap) throws UnsupportedEncodingException {
        return makeSign(signSalt, parameterMap);
    }


    /**
     * 验证签名
     *
     * @param sign
     * @param parameterMap
     * @return
     * @throws UnsupportedEncodingException
     */
    public static boolean verifySign(String sign, Map<String, Object> parameterMap) throws UnsupportedEncodingException {
        return makeSign(signSalt, parameterMap).equals(sign);
    }


    /**
     * 验证签名 boss系统
     */
    public static boolean verifySignBoss(String sign, Map<String, Object> parameterMap) throws UnsupportedEncodingException {
        return makeSign(BOOS_SIGN_SALT, parameterMap).equals(sign);
    }


    public static String toMD5(String str) {
        try {
            return DigestUtils.md5DigestAsHex(str.getBytes("utf-8")).toUpperCase();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String escape(String src) {
        int i;
        char j;
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length() * 6);

        for (i = 0; i < src.length(); i++) {

            j = src.charAt(i);

            if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j)) {
                tmp.append(j);
            } else if (j < 256) {
                tmp.append("%");
                if (j < 16) {
                    tmp.append("0");
                }
                tmp.append(Integer.toString(j, 16));
            } else {
                tmp.append("%u");
                tmp.append(Integer.toString(j, 16));
            }
        }
        return tmp.toString();
    }

    public static String unescape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }

    public static void main(String[] args) throws Exception {
        String str = "...123asdf1#$%^&(中午你____".replaceAll("[^\\w]", "_");


        System.out.println(str);


        String sb = "110a111b22sessionToken5e4c6d0507bc5fad86cc8d63e8e9ab93110";

        String sign = DigestUtils.md5DigestAsHex(sb.replaceAll("[^\\w]", "").getBytes("utf-8")).toUpperCase();

        System.out.println(sign);

    }

}

